/*
 *  $Id$
 *  Copyright [2010] [Panxiaobo] 
 *  Licensed under the Apache License, Version 2.0 (the "License"); 
 *  you may not use this file except in compliance with the License. 
 *  You may obtain a copy of the License at
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 *  Unless required by applicable law or agreed to in writing, software 
 *  distributed under the License is distributed on an "AS IS" BASIS, 
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 *  See the License for the specific language governing permissions and 
 *  limitations under the License. 
 */
package pxb.openid.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;

import pxb.openid.OpenIdException;

/**
 * 工具类
 * 
 * @author Panxiaobo
 * 
 */
public class Util {
    public static BigInteger Base64ToBigInteger(String bi) {
        return new BigInteger(Base64.decodeBase64(bi.getBytes()));
    }

    public static String BigIntegerToBase64(BigInteger bi) {
        return new String(Base64.encodeBase64(bi.toByteArray()));
    }

    /**
     * 验证全部不为null
     * 
     * @param msg
     * @param values
     */
    public static void checkNotNull(String msg, Object... values) {
        for (Object o : values) {
            if (o == null)
                throw new OpenIdException(msg);
        }
    }

    /**
     * 验证不为null
     * 
     * @param msg
     * @param value
     */
    public static void checkNotNull(String msg, Object value) {
        if (value == null)
            throw new OpenIdException(msg);
    }

    /**
     * shax签名
     * 
     * @param x
     * @param data
     * @return
     */
    public static byte[] sha(int x, byte[] data) {
        try {
            MessageDigest sha = MessageDigest.getInstance("SHA-" + x);
            return sha.digest(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] xorsha(int x, BigInteger shared, byte[] key) {
        return xorsha(x, shared.toByteArray(), key);
    }

    public static byte[] xorsha(int x, byte[] data, byte[] key) {
        return xor(sha(x, data), key);
    }

    public static String ToBase64(byte[] b) {
        return new String(Base64.encodeBase64(b));
    }

    /**
     * 构造请求url
     * 
     * @param server
     *            服务器
     * @param parms
     *            请求参数
     * @return
     */
    public static String ToURL(String server, Map<String, String> parms) {
        try {
            StringBuilder sb = new StringBuilder(server);
            Iterator<Map.Entry<String, String>> it = parms.entrySet().iterator();
            Map.Entry<String, String> entry;
            // first
            if (it.hasNext()) {
                entry = it.next();
                if (parms.size() > 0) {
                    sb.append(sb.indexOf("?") > 0 ? '&' : '?');
                }
                if (entry.getValue() == null || entry.getKey() == null) {
                    throw new RuntimeException("there is null in params : " + entry.getKey() + " =  "
                            + entry.getValue());
                }
                sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append('=')
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }
            while (it.hasNext()) {
                entry = it.next();
                if (entry.getValue() == null || entry.getKey() == null) {
                    throw new RuntimeException("there is null in params : " + entry.getKey() + " =  "
                            + entry.getValue());
                }
                sb.append('&').append(URLEncoder.encode(entry.getKey(), "UTF-8")).append('=')
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
            }

            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            throw new OpenIdException("不支持编码方式", e);
        }
    }

    public static byte[] xor(byte[] a, byte[] b) {
        if (a.length != b.length) {
            throw new RuntimeException("lengh of array not same");
        }
        byte[] c = new byte[a.length];
        for (int i = 0; i < a.length; i++) {
            c[i] = (byte) (a[i] ^ b[i]);
        }
        return c;
    }
}
